package com.wejoy.video.middle.station.admin.controller.res;

import com.wejoy.video.middle.station.admin.controller.BaseController;
import com.wejoy.video.middle.station.admin.util.CurrentUserUtils;
import com.wejoy.video.middle.station.data.annotation.RoleCheck;
import com.wejoy.video.middle.station.data.domain.PageResult;
import com.wejoy.video.middle.station.data.domain.res.PhotoResLib;
import com.wejoy.video.middle.station.data.domain.system.SysUser;
import com.wejoy.video.middle.station.data.enums.dict.EnumStatus;
import com.wejoy.video.middle.station.data.enums.dict.MultiMediaUploaderType;
import com.wejoy.video.middle.station.data.enums.file.EnumUpload;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.service.file.IFileService;
import com.wejoy.video.middle.station.data.service.res.IPhotoResLibService;
import com.wejoy.video.middle.station.data.util.WJAssert;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图片资源库
 *
 * @author Administrator
 * @date 2021年10月20日 18:11:17
 */
@RestController
@RequestMapping("/res/photoResLib")
public class PhotoResLibController extends BaseController {

    @Autowired
    private IPhotoResLibService photoResLibService;

    private static final String PHOTO_RESLIB_MAP = "photoReslibMap";
    @Autowired
    private IFileService fileService;

    /**
     * 保存或更新
     *
     * @param photoResLibReq photoResLibReq
     * @return RespJSON
     */
    @PostMapping("/save")
    @RoleCheck(name = "photoResLib_edit,photoResLib_add")
    public RespJSON save(@RequestBody PhotoResLib photoResLibReq, @SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        photoResLibReq.setCreateUserId(loginSysUser.getName());
        photoResLibReq.setDataStatus(EnumStatus.AUDIT.getCode());
        photoResLibReq.setUploaderType(MultiMediaUploaderType.INNER_UPLOADER.getCode());
        photoResLibService.save(photoResLibReq, loginSysUser.getUserName());
        return RespJSON.success();
    }

    /**
     * 分页查询
     *
     * @param photoResLibReq photoResLibReq
     * @return RespJSON
     */
    @PostMapping("/getPageList")
    @RoleCheck(name = "photoResLib_list")
    public RespJSON getPageList(@RequestBody PhotoResLib photoResLibReq) {
        int count = photoResLibService.getCount(photoResLibReq);
        List<PhotoResLib> list = new ArrayList<>();
        if (count > 0) {
            list = photoResLibService.getPageList(photoResLibReq);
        }
        PageResult result = new PageResult(photoResLibReq.getPageNo(), photoResLibReq.getPageSize(), count, list);
        return RespJSON.success(result);
    }

    @PostMapping("/saveList")
    @RoleCheck(name = "photoResLib_edit,photoResLib_add")
    public RespJSON saveList(@RequestBody Map<String, List<PhotoResLib>> photoReslibMap, @SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        photoReslibMap.get(PHOTO_RESLIB_MAP).forEach(photo -> {
            photo.setDataStatus(EnumStatus.AUDIT.getCode());
            photo.setCreateUserId(loginSysUser.getName());
            photo.setUploaderType(MultiMediaUploaderType.INNER_UPLOADER.getCode());
            photoResLibService.save(photo, loginSysUser.getUserName());
        });
        return RespJSON.success();
    }

    /**
     * 主键查询
     *
     * @param id id
     * @return RespJSON
     */
    @RequestMapping("/getOneById")
    @RoleCheck(name = "photoResLib_list")
    public RespJSON getOneById(Long id) {
        return RespJSON.success(photoResLibService.getOneById(id));
    }

    /**
     * 审核
     *
     * @param id id
     * @return RespJSON
     */
    @PostMapping("/audit")
    @ResponseBody
    public RespJSON audit(Long id, @SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        WJAssert.notNull(id, "ID 不合法");
        photoResLibService.audit(id, loginSysUser.getUserName());
        return RespJSON.success();
    }

    /**
     * 取消审核
     *
     * @param id id
     * @return RespJSON
     */
    @PostMapping("/unaudit")
    @ResponseBody
    public RespJSON unaudit(Long id, @SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        WJAssert.notNull(id, "ID 不合法");
        photoResLibService.unaudit(id, loginSysUser.getUserName());
        return RespJSON.success();
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @RoleCheck(name = "photoResLib_delete")
    public RespJSON delete(Long id, @SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        WJAssert.notNull(id, "ID 不合法");
        photoResLibService.delete(id, loginSysUser.getUserName());
        return RespJSON.success();
    }

    /**
     * base64 转成图片
     *
     * @param base64Url base64图片数据
     * @return
     */
    @PostMapping("/generateImage")
    @ResponseBody
    public RespJSON GenerateImage(String base64Url, @SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) throws IOException {
        if (StringUtils.isEmpty(base64Url)) {
            throw new BusinessException("图片BASE64错误");
        }
        //过滤base64前缀
        String imgbese64 = base64Url.replace("data:image/png;base64,", "");
        // 图像数据为空
        if (imgbese64 == null) {
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        // Base64解码
        byte[] b = decoder.decodeBuffer(imgbese64);
        for (int i = 0; i < b.length; ++i) {
            // 调整异常数据
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        InputStream inputStream = new ByteArrayInputStream(b);
        MultipartFile file = null;
        try {
            file = new MultipartFile() {
                @Override
                public String getName() {
                    return "tmp.jpg";
                }

                @Override
                public String getOriginalFilename() {
                    return "tmp.jpg";
                }

                @Override
                public String getContentType() {
                    return ContentType.APPLICATION_OCTET_STREAM.toString();
                }

                @Override
                public boolean isEmpty() {
                    return false;
                }

                @Override
                public long getSize() {
                    return b.length;
                }

                @Override
                public byte[] getBytes() throws IOException {
                    return b;
                }

                @Override
                public InputStream getInputStream() throws IOException {
                    return inputStream;
                }

                @Override
                public void transferTo(File dest) throws IOException, IllegalStateException {

                }
            };
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
        String key = fileService.upload(EnumUpload.RES_PHOTO_LIB, file.getBytes()).getKey();
        return RespJSON.success(key);
    }


    /**
     * 模态窗口上传图片
     *
     * @param imgFile 图片
     * @param inputId 之前触发选择图片页面的input框的inputId
     * @return
     */
    @RequestMapping(value = "/modalUploadSave", method = RequestMethod.POST)
    @ResponseBody
    public RespJSON modalUploadSave(PhotoResLib photoResLib,
                                    MultipartFile imgFile,
                                    @RequestParam(value = "inputId", defaultValue = "", required = false) String inputId,
                                    String base64Url, @SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        photoResLib.setCreateUserId(loginSysUser.getUserName());
        photoResLibService.save(photoResLib, imgFile, base64Url);
        Map resultMap = new HashMap<>();
        resultMap.put("inputId", inputId);
        return RespJSON.success(resultMap);

    }
}
